package org.com.db.core;

import java.util.ArrayList;
import java.util.List;

import org.com.db.api.GetDataComponet;
import org.com.db.domain.ProduceType;
import org.com.db.exception.DBException;
import org.com.db.exception.DBMSG;
import org.com.db.util.DBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class GetDataComponetImpl implements GetDataComponet {
	private static final String TAG = null;
	private DBHelper dbHelper;

	public GetDataComponetImpl(Context context) {
		this.dbHelper = new DBHelper(context);
	}

	@Override
	public ProduceType getProduceByObjectId(String objectId) throws DBException {

		final List<ProduceType> produces = new ArrayList<ProduceType>();
		final SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = null;
		try {

			final String SQL = "SELECT * FROM Produce WHERE ObjectId=?";
			cursor = db.rawQuery(SQL, new String[] { objectId });
			cursor.moveToFirst();

			for (int i = 0; i < cursor.getCount(); i++) {

				final ProduceType produce = new ProduceType();
				produce.setPrice(this.getString(cursor, "price"));
				produce.setPic(this.getString(cursor, "pic"));
				produce.setName(this.getString(cursor, "name"));
				produce.setDescribe(this.getString(cursor, "describe"));
				produce.setObjectId(this.getString(cursor, "objectId"));

				produces.add(produce);

				cursor.moveToNext();
			}

			if (produces.size() == 0) {
				return null;
			} else {
				return produces.get(0);
			}

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new DBException(DBMSG.DB_ERROR002);
		} finally {
			cursor.close();
			db.close();

		}

	}

	private String getString(Cursor cursor, String name) {
		return cursor.getString(cursor.getColumnIndex(name));
	}

	@Override
	public List<ProduceType> getProduce() throws DBException {
		final List<ProduceType> produces = new ArrayList<ProduceType>();
		final SQLiteDatabase db = dbHelper.getReadableDatabase();

		try {

			final String SQL = "SELECT * FROM Produce  ";
			Cursor cursor = db.rawQuery(SQL, new String[] {});
			while (cursor.moveToNext()) {
				final ProduceType produce = new ProduceType();
				produce.setPrice(this.getString(cursor, "price"));
				produce.setPic(this.getString(cursor, "pic"));
				produce.setName(this.getString(cursor, "name"));
				produce.setDescribe(this.getString(cursor, "describe"));
				produce.setObjectId(this.getString(cursor, "objectId"));

				produces.add(produce);
			}
			return produces;

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new DBException(DBMSG.DB_ERROR002);
		} finally {
			db.close();
		}

	}

}
